package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;

@WebServlet(name = "UpdateDisplayNameControllerServlet", urlPatterns = "/UpdateDisplayNameControllerServlet")
public class UpdateDisplayNameControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -7341195930575984509L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			String loginId = request.getParameter("loginid");
			String displayName = request.getParameter("displayname");

			User user = User.get(request.getUserPrincipal().getName());

			if (displayName.length() > 80) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", "Display name must be less than 80 characters.");
				dispatcher.forward(request, response);
				return;
			}

			if ((!Configuration.getInstance().isAllowChangeOfUserName()) && (!user.isSiteAdmin())) {
				return;
			}

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			/*
			 * If it's an admin updating someone else's display name then update
			 * the original display name
			 */

			if (user.isSiteAdmin() && (!user.getLoginId().equalsIgnoreCase(loginId))) {
				user.updateOriginalDisplayName(displayName);
			}

			User toBeChanged = User.get(loginId);
			boolean completed = toBeChanged.changeDisplayName(displayName);

			if (!completed) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", "Please don't use the following characters in your display name: <, >, &, %, ', \", `, !, #, {, }, [, ].");
				dispatcher.forward(request, response);
				return;
			}

			response.sendRedirect(request.getHeader("referer"));

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
